package cn.lijigou.shopping;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;

import cn.lijigou.shopping.domain.MResult;
import cn.lijigou.shopping.domain.Order;
import cn.lijigou.shopping.service.MSystem;
import cn.lijigou.shopping.util.GetSingleThreadPool;
import cn.lijigou.shopping.util.LoadImageAysnc;
import cn.lijigou.shopping.util.LoadImageAysnc.ImageCallBack;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.opengl.Visibility;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;

public class OrdersActivity extends MActivity implements OnClickListener {
	public static  int NOT_HAVE_ORDER_DATE = 0;
	public static final int NOTIFY_DATA_SET_CHANGED = 1;
	private TextView title_btn_left= null;
	private LinearLayout titleLeftView= null;
	private TextView title_btn_right= null;
 

	private LinearLayout titleRightView= null;
	private TextView text_center= null;
	
	public static int radioButtonId=1;
	public static RadioButton mButton_paid = null;
	public static RadioButton mButton_unpaid = null;
	
	private ListView mListView;
	public static MyAdapter mAdapter;
	public static int[] pages = {0,0};
	public static boolean[] hasNextPages = {true,true};
	private List<String> recordError=new ArrayList<String>();
	
	private Order order;
	private TextView mWaitContent;
	private TextView mListEmpty;
	private LinearLayout mBottom_linear;
	private RelativeLayout mRegister_linear = null;
	private Button mRegister_button = null;
	public TextView tv;
	private View mFootView;
	private View load_one;
	private View load_two;
	
	public static List<List<Order>> orders = new ArrayList<List<Order>>();
	public static List<Order> mPayedOrders = new ArrayList<Order>();
	public static List<Order> mUnPayOrders = new ArrayList<Order>();
	private MainTabActivity parentView;
	private ExecutorService executorService = GetSingleThreadPool.getInstance();
	
	
	public Handler waitHander = new Handler() {
		
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == NOTIFY_DATA_SET_CHANGED) {
				titleRightView.setEnabled(true);
				if ((mPayedOrders.size() > 0&&radioButtonId==1) ||(mUnPayOrders.size() > 0&&radioButtonId==1)) {
					if (MSystem.isLoginDummy(OrdersActivity.this)) {
						mRegister_linear.setVisibility(View.VISIBLE);
					} else {
						mRegister_linear.setVisibility(View.GONE);
					}
				}
				mListEmpty.setVisibility(View.GONE);
//				load_one.setVisibility(View.GONE);
//				load_two.setVisibility(View.GONE);
				mAdapter.setDate(orders.get(radioButtonId));
				mAdapter.notifyDataSetChanged();
			} else if (msg.what == NOT_HAVE_ORDER_DATE) {
				titleRightView.setEnabled(true);
				mListEmpty.setVisibility(View.VISIBLE);
				if(radioButtonId ==1){
					if(mPayedOrders.size()==0){
						mListEmpty.setText("您还没有已支付订单");
					}
				}else{
					if(mUnPayOrders.size()==0){
						mListEmpty.setText("您还没有未支付订单");
					}
				}
				load_one.setVisibility(View.GONE);
				load_two.setVisibility(View.GONE);
				mRegister_linear.setVisibility(View.GONE);
			} else if(msg.what == 3){
				Toast.makeText(OrdersActivity.this, "网络连接有异常", 1).show();
				mListEmpty.setVisibility(View.GONE);
				load_one.setVisibility(View.GONE);
				load_two.setVisibility(View.VISIBLE);
			} else if(msg.what==4){
				mListEmpty.setVisibility(View.GONE);
				load_one.setVisibility(View.VISIBLE);
				load_two.setVisibility(View.GONE);
			} else if(msg.what==5){
				mListEmpty.setVisibility(View.GONE);
				load_one.setVisibility(View.GONE);
				load_two.setVisibility(View.GONE);
			} else if(msg.what == 6){
				
				titleRightView.setEnabled(true);
				mListEmpty.setVisibility(View.VISIBLE);
				if(radioButtonId ==1){
					
					mListEmpty.setText("您还没有已支付订单");
				}else{
					mListEmpty.setText("您还没有未支付订单");
				}
				load_one.setVisibility(View.GONE);
				load_two.setVisibility(View.GONE);
				mRegister_linear.setVisibility(View.GONE);
				
			}
		}
	};
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.orders);
		overridePendingTransition(R.anim.push_in, R.anim.push_out);
		pages[0] = 1;
		pages[1] = 1;
		radioButtonId =1;
		mPayedOrders.clear();
		mUnPayOrders.clear();
		hasNextPages[0]=true;
		hasNextPages[1]=true;
		orders.add(mUnPayOrders);
		orders.add(mPayedOrders);
		
		initView();
		getOrders();
	}
	private void initView() {
		title_btn_left = (TextView) this.findViewById(R.id.title_btn_left);
		titleLeftView = (LinearLayout) this.findViewById(R.id.titleLeftView);
		title_btn_left.setBackgroundResource(R.drawable.title_back_normal);

		titleLeftView.setVisibility(View.GONE);
		title_btn_right = (TextView) this.findViewById(R.id.title_btn_right);
		titleRightView = (LinearLayout) this.findViewById(R.id.titleRightView);
		title_btn_right.setText("");
		title_btn_right.setBackgroundResource(R.drawable.title_refresh);
		titleRightView.setOnClickListener(this);
		text_center = (TextView) this.findViewById(R.id.text_center);
		text_center.setText(R.string.my_orders);
		
		mWaitContent = (TextView) findViewById(R.id.wait_content);
		mListEmpty = (TextView) findViewById(R.id.list_empty);
		mBottom_linear = (LinearLayout) findViewById(R.id.bottom_linear);
		mRegister_linear = (RelativeLayout) this.findViewById(R.id.register_linear);
		mRegister_button = (Button) this.findViewById(R.id.button_register);
		mRegister_button.setOnClickListener(this);
		
		mButton_paid = (RadioButton) this.findViewById(R.id.button_paid);
		mButton_unpaid = (RadioButton) this.findViewById(R.id.button_unpaid);
		mButton_paid.setOnClickListener(this);
		mButton_unpaid.setOnClickListener(this);

		parentView=(MainTabActivity)OrdersActivity.this.getParent();
		
		mFootView = LayoutInflater.from(this).inflate(R.layout.list_bottom_line, null);
		load_one = mFootView.findViewById(R.id.load_one);
		load_two = mFootView.findViewById(R.id.load_two);
		load_two.setOnClickListener(this);
		mListView = (ListView) findViewById(R.id.list);
		mListView.addFooterView(mFootView);
		mAdapter = new MyAdapter(this,mPayedOrders,mListView);
		mListView.setAdapter(mAdapter);
		mListView.setOnScrollListener(listScrollListener);
		mListView.setOnItemClickListener(mClickListener);
	}

	
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if(mPayedOrders.size() == 0 | mUnPayOrders.size() == 0){
			getOrders();
		}
		
	}
	
	protected void onRestart() {
		super.onRestart();
		mAdapter.notifyDataSetChanged();

	}

	private void getOrders() {
		MSystem.isLogin(this, 0);
		if(isNull(MSystem.uid)){
			if(recordError.contains(radioButtonId+"")){
				recordError.remove(radioButtonId+"");
				hasNextPages[radioButtonId]=true;
			}
			if (hasNextPages[radioButtonId]) {
				hasNextPages[radioButtonId] = false;
				if (getNetConnectState(OrdersActivity.this)) {
					executorService.execute(new Thread() {
						public void run() {
							waitHander.sendEmptyMessage(4);
							Boolean temp = false;
							if (orders.get(radioButtonId).size() == 0) {
								pages[radioButtonId] = 1;
							} else {
								pages[radioButtonId] = pages[radioButtonId] + 1;
							}
							MResult mResult = MSystem.getOrders(orders.get(radioButtonId), pages[radioButtonId], radioButtonId);
							if (mResult != null) {
								if (mResult.isSuccess()) {
									temp = mResult.isPage();
									waitHander.sendEmptyMessage(NOTIFY_DATA_SET_CHANGED);
									if (!temp) {
										waitHander.sendEmptyMessage(5);
										MainTabActivity.showHander.sendEmptyMessage(102);
									}

								} else {
									if (orders.get(radioButtonId).size() > 0) {
										MainTabActivity.showHander.sendEmptyMessage(102);
									}
									recordError.add(radioButtonId + "");
									waitHander.sendEmptyMessage(6);
								}
							} else {
								if (orders.get(radioButtonId).size() == 0) {
									pages[radioButtonId] = 1;
								} else {
									pages[radioButtonId] = pages[radioButtonId] - 1;
								}
								recordError.add(radioButtonId + "");
								waitHander.sendEmptyMessage(3);

							}
							hasNextPages[radioButtonId] = temp;
						}
					});
				} else {
					recordError.add(radioButtonId + "");
					waitHander.sendEmptyMessage(3);
				}

			}
		}else{
			waitHander.sendEmptyMessage(6);
		}
		
	}
	private class ViewHolder {
		private ImageView img;
		private TextView info;
		private TextView total_price;
		private TextView saved_price;
		private TextView distance;
		private TextView address;
		private TextView source;
		
	}

	public class MyAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		private List<Order> orderList;
		LoadImageAysnc loadImageAysnc;
		ListView listView;
		public MyAdapter(Activity context,List<Order> orderList,ListView listView) {
			this.orderList=orderList;
			this.mInflater = LayoutInflater.from(context);
			loadImageAysnc = new LoadImageAysnc(context);
			this.listView=listView;
		}

		public int getCount() {
			return orderList.size();
		}
		public void setDate(List<Order> orderList) {
			 this.orderList=orderList;
		}
		
		public Object getItem(int arg0) {
			return null;
		}

		public long getItemId(int arg0) {
			return 0;
		}
		

		ViewHolder holder = null;

		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null || convertView.getTag() == null) {
				holder = new ViewHolder();
				convertView = mInflater
						.inflate(R.layout.list_item_orders, null);
				holder.img = (ImageView) convertView.findViewById(R.id.img);
				holder.info = (TextView) convertView.findViewById(R.id.info);
				holder.total_price = (TextView) convertView.findViewById(R.id.total_price);
				holder.saved_price = (TextView) convertView.findViewById(R.id.saved_price);
				holder.distance = (TextView) convertView.findViewById(R.id.distance);
				holder.address = (TextView) convertView.findViewById(R.id.address);
				holder.source = (TextView) convertView.findViewById(R.id.source);
				holder.distance.setVisibility(View.GONE);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			
			order = orderList.get(position);

			String total_price = order.getTotal_price();
			String title = order.getTuan_title();
			String strSource = order.getTuan_site();
			String strAddress = order.getAddress();
			final String id=order.getTuan_id();
			holder.img.setTag(id);
			
			
			
			//开始异步加载数据
			Drawable drawable = loadImageAysnc.loadImage(position,orderList.get(position).getId(), orderList.get(position).getImage(), "small.jpg",new ImageCallBack() {
				
				public void imageLoaded(Drawable drawable, int position) {
					// TODO Auto-generated method stub
					ImageView imageViewTag = (ImageView) listView.findViewWithTag(id);
					if(imageViewTag != null) {
						imageViewTag.setBackgroundDrawable(drawable);
					}
					ProgressBar progressBar = (ProgressBar) listView.findViewWithTag(order.getImage());
					if(progressBar != null) {
						progressBar.setVisibility(View.GONE);
					}
				}
			} );
			
			
			if(drawable == null) {
				 holder.img.setBackgroundResource(R.drawable.load_small);
			} else {
				 holder.img.setBackgroundDrawable(drawable);
			}
			holder.address.setText(strAddress);
			
			if(isNull(strSource)){
				holder.source.setText(strSource);
			}else{
				holder.source.setVisibility(View.GONE);
			}
			
			if (isNull(title)) {
				holder.info.setText(title + "...");
			}else{
				holder.info.setText("暂无详情");
			}
			if(isNull(total_price)&&!total_price.equals(getStringToResource(R.string.No_).trim())){
				holder.total_price.setText("￥" + total_price);
			}else{
				holder.total_price.setText("");
			}
			
			
			convertView.invalidate();
			return convertView;
		}
		
	}

	/**
	 * ListView 中某项被选中后的逻辑
	 */
	private OnItemClickListener mClickListener = new OnItemClickListener() {

		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			MSystem.pv += 1;
			if (view != mFootView) {
				Intent intent = new Intent(OrdersActivity.this, OrderDetailActivity.class);
				intent.putExtra("position", position);
				if (radioButtonId == 0) {
					intent.putExtra("isPaid", false);
				} else {
					intent.putExtra("isPaid", true);
				}
				OrdersActivity.this.startActivityForResult(intent, 1);
			}

		}
	};
	public Boolean isNull(String str) {
		if (str != null && !str.equals("") && str != "" && str != "null") {
			return true;
		}
		return false;
	}

	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		
		if (requestCode == 1) {
			if(!hasNextPages[0]){
				waitHander.sendEmptyMessage(5);
			}else if(!hasNextPages[1]){
				waitHander.sendEmptyMessage(5);
			}
		}
	}

	private OnScrollListener listScrollListener = new ListView.OnScrollListener() {
		public void onScroll(AbsListView arg0, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			
			if (totalItemCount <= 0) {
				return;
			}
			if (firstVisibleItem + visibleItemCount >= totalItemCount) {
				if (hasNextPages[radioButtonId]) {
					getOrders();
				}
				
			}
		}

		public void onScrollStateChanged(AbsListView view, int scrollState) {
			if(scrollState==0){
				waitHander.sendEmptyMessage(1);
			}
		}
	};
	
	  
	    public boolean onKeyDown(int keyCode, KeyEvent event) {
	    	if (keyCode == KeyEvent.KEYCODE_BACK) {
	  			Animation animation=AnimationUtils.loadAnimation(OrdersActivity.this,R.anim.home_push_rightout);
  			parentView.mHost.getCurrentView().startAnimation(animation);
      		parentView.mHost.setCurrentTab(0);	
  			parentView.main_tab_home.setChecked(true);
			    Animation animations=AnimationUtils.loadAnimation(OrdersActivity.this,R.anim.home_push_rightin);
			    parentView.mHost.getCurrentView().startAnimation(animations);
	    		return true;
		    }else{
		    	return super.onKeyDown(keyCode, event);
		    }
	    }
	public String getStringToResource(int id){
		String string=this.getResources().getString(id);
		return string;
	}
	public boolean getNetConnectState(Context context) {
		boolean netConnect = false;
		ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		NetworkInfo infoM = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		if (info.isConnected() || infoM.isConnected()) {
			netConnect = true;
		}
		return netConnect;
	}
	
	
	public void onClick(View v) {
		MSystem.pv += 1;
		switch (v.getId()) {
		case R.id.title_btn_left:
			this.finish();
			break;
		case R.id.titleRightView:
			
			v.setEnabled(false);
			pages[0] = 0;
			pages[1] = 0;
			hasNextPages[0] = true;
			hasNextPages[1] = true;
			mPayedOrders.clear();
			mUnPayOrders.clear();
			mAdapter.setDate(new ArrayList<Order>());
			mAdapter.notifyDataSetChanged();
			getOrders();
			break;
		case R.id.button_register:
			Intent mIntent = new Intent(OrdersActivity.this, RegisterActivity.class);
			OrdersActivity.this.startActivity(mIntent);
			break;
		case R.id.button_paid:
			
			radioButtonId = 1;
			mListView.setSelection(0);
			if(mPayedOrders.size() == 0){
				mAdapter.setDate(new ArrayList<Order>());
				mAdapter.notifyDataSetChanged();
				getOrders();
			}else{
				waitHander.sendEmptyMessage(NOTIFY_DATA_SET_CHANGED);
			}
			
			if(!hasNextPages[0]){
				waitHander.sendEmptyMessage(5);
			}else if(!hasNextPages[1]){
				waitHander.sendEmptyMessage(5);
			}
			break;
		case R.id.button_unpaid:
			
			
			radioButtonId = 0;
			mListView.setSelection(0);
			if(mUnPayOrders.size() == 0){
				mAdapter.setDate(new ArrayList<Order>());
				mAdapter.notifyDataSetChanged();
				getOrders();
			}else{
				waitHander.sendEmptyMessage(NOTIFY_DATA_SET_CHANGED);
			}
			
			if(!hasNextPages[0]){
				waitHander.sendEmptyMessage(5);
			}else if(!hasNextPages[1]){
				waitHander.sendEmptyMessage(5);
			}
			break;
		case R.id.load_two:
			getOrders();
			
			break;
		default:
			break;
		}
	}
	
	
}
